/*
 * 文件名：MonthCtrlController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：chenhan
 * 修改时间：2020年1月13日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.ic.web;


import com.github.pagehelper.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import top.infopub.mgr.bpa.service.SubpackCotService;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.ic.domain.MonthCtrlDomain;
import top.infopub.mgr.ic.service.*;
import top.infopub.mgr.ic.vo.MonthCtrlVo;
import top.infopub.mgr.sg.service.CitySurveyService;
import top.infopub.mgr.util.DateUtils;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.ic.*;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 投建月度管控
 *
 * @author wangw
 * @version 2020年1月16日
 * @see MonthCtrlController
 * @since
 */
@Controller
@RequestMapping("/monthCtrl")
public class MonthCtrlController extends GenericFlowController {

    @Autowired
    private MonthCtrlService monthCtrlService;

    @Autowired
    private MonthCtrlSubService monthCtrlSubService;

    @Autowired
    private MonthCtrlMileService monthCtrlMileService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private ProgramPlanService programPlanService;

    @Autowired
    private ProgramPlanSubService programPlanSubService;

    @Autowired
    private SubpackCotService subpackCotService;

    @Autowired
    private CitySurveyService citySurveyService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    /**
     * 投建月度管控列表
     *
     * @return
     * @see
     */
    @RequestMapping("/list")
    public String list() {
        return "ic/lay-monthCtrl-list";
    }

    /**
     * 投建月度管控列表
     *
     * @param monthCtrlVo
     * @param paramPage
     * @return
     * @throws ParseException 
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<MonthCtrlDomain> queryDataByCondition(MonthCtrlVo monthCtrlVo, ParamPage paramPage,
        String ctrlMonthStart, String ctrlMonthEnd) throws ParseException {

        Page<MonthCtrlDomain> page = new Page<>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        if (monthCtrlVo.getEndDate() != null) {
            monthCtrlVo.setEndDate(DateUtils.addDays(monthCtrlVo.getEndDate(), 1));
        }
        if(StringUtils.isNotEmpty(ctrlMonthStart)){
            Date startDate = DateUtils.parseDate(ctrlMonthStart, "yyyy-MM");
            monthCtrlVo.setCtrlMonthStartDate(startDate);
        }
        if(StringUtils.isNotEmpty(ctrlMonthEnd)){
            Date endDate = DateUtils.parseDate(ctrlMonthEnd, "yyyy-MM");
            Date stsMonthEnd = DateUtils.getMonthEnd(endDate);
            monthCtrlVo.setCtrlMonthEndDate(stsMonthEnd);
        }
        page = monthCtrlService.selectByDomainWhere(page, monthCtrlVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 查询我审批的投建月度管控
     *
     * @param monthCtrlVo
     * @param paramPage
     * @return
     * @throws ParseException 
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<MonthCtrlDomain> queryMyCheckDataByCondition(MonthCtrlVo monthCtrlVo,ParamPage paramPage,
        String ctrlMonthStart, String ctrlMonthEnd) throws ParseException {
        Page<MonthCtrlDomain> page = new Page<>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (monthCtrlVo.getEndDate() != null) {
            monthCtrlVo.setEndDate(DateUtils.addDays(monthCtrlVo.getEndDate(), 1));
        }
        if(StringUtils.isNotEmpty(ctrlMonthStart)){
            Date startDate = DateUtils.parseDate(ctrlMonthStart, "yyyy-MM");
            monthCtrlVo.setCtrlMonthStartDate(startDate);
        }
        if(StringUtils.isNotEmpty(ctrlMonthEnd)){
            Date endDate = DateUtils.parseDate(ctrlMonthEnd, "yyyy-MM");
            Date stsMonthEnd = DateUtils.getMonthEnd(endDate);
            monthCtrlVo.setCtrlMonthEndDate(stsMonthEnd);
        }
        // 增加addby
        monthCtrlVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = monthCtrlService.selectMyCheckByDomainWhere(page, monthCtrlVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 新增投建月度管控页
     *
     * @param request
     * @return
     */
    @RequestMapping("/add")
    public String toAdd(HttpServletRequest request) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //返回所有项目工程计划项目
        ProgramPlan programPlan = new ProgramPlan();
        programPlan.setProcessStatus("9");
        List<ProgramPlan> programPlans = programPlanService.selectByEntityWhere(programPlan);
        request.setAttribute("programPlans", programPlans);
        return "ic/lay-monthCtrl-add";
    }

    /**
     * 投建月度管控-新增
     * @throws ParseException 
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/save")
    public @ResponseBody RspVo save(HttpServletRequest request, MonthCtrlVo monthCtrl)
        throws ParseException {
        //分包合同相关字段
        String[] cotNameArray = request.getParameterValues("cotName");//合同名称
        String[] orgNameArray = request.getParameterValues("orgName");//单位名称
        String[] subpackPayRateArray = request.getParameterValues("subpackPayRate");//分包付款完成率

        //子项相关字段
        String[] subIdArray = request.getParameterValues("subId");//子项id
        String[] subNameArray = request.getParameterValues("subName");//子项名称
        String[] subOrderIdxArray = request.getParameterValues("subOrderIdx");//子项序号

        //获取节点各字段信息
        String[] showOrderIdxeArray = request.getParameterValues("showOrderIdx");//节点序号
        String[] levelIdxeArray = request.getParameterValues("levelIdx");//节点等级
        String[] ctrlSubIdArray = request.getParameterValues("ctrlSubId");//子项id
        String[] pointNameArray = request.getParameterValues("pointName");//工作节点
        String[] memoArray = request.getParameterValues("memo");//单体/分区说明
        String[] planStartTimeArray = request.getParameterValues("planStartTime");//计划开始日期
        String[] planFinishTimeArray = request.getParameterValues("planFinishTime");//计划完成日期
        String[] actFinishTimeArray = request.getParameterValues("actFinishTime");//实际完成日期
        String[] delayDaysArray = request.getParameterValues("delayDays");//延误天数
        String[] finishFlagArray = request.getParameterValues("finishFlag");//完成情况

        String id = IdFactory.getUUIDUpper();
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String delayDaysMax = request.getParameter("delayDaysMax");
        monthCtrl.setId(id);
        monthCtrl.setDelayDays(Integer.parseInt(delayDaysMax));
        String codes = codeGeneratorConfigService.generatorCode("ic_month_ctrl_codes");
        monthCtrl.setCodes(codes);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        monthCtrl.setCtrlMonth(simpleDateFormat.parse(request.getParameter("ctrlMonthStr")));
        // 处理processId
        monthCtrl.setProcessId(IdFactory.getUUIDUpper());
        monthCtrl.setProcessStatus("1");//审批中
        monthCtrl.setAddBy(vo.getId());
        monthCtrl.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        monthCtrl.setUptBy(vo.getId());
        monthCtrl.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        List<MonthCtrlSubpack> monthCtrlSubpacks = new LinkedList<>();
        if (cotNameArray != null) {
            for (int i = 0; i < cotNameArray.length; i++ ) {
                MonthCtrlSubpack monthCtrlSubpack = new MonthCtrlSubpack();
                monthCtrlSubpack.setId(IdFactory.getUUIDUpper());
                monthCtrlSubpack.setMonthCtrlId(id);
                monthCtrlSubpack.setCotName(cotNameArray[i]);
                monthCtrlSubpack.setOrgName(orgNameArray[i]);
                monthCtrlSubpack.setSubpackPayRate(new BigDecimal(subpackPayRateArray[i]));
                monthCtrlSubpack.setAddBy(vo.getId());
                monthCtrlSubpack.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                monthCtrlSubpacks.add(monthCtrlSubpack);
            }
        }

        List<MonthCtrlSub> monthCtrlSubs = new LinkedList<>();
        //节点数据处理
        List<MonthCtrlMile> monthCtrlMiles = new LinkedList<>();
        if (subIdArray != null) {
            for (int i = 0; i < subIdArray.length; i++ ) {
                MonthCtrlSub monthCtrlSub = new MonthCtrlSub();
                monthCtrlSub.setMonthCtrlId(id);
                String uuidUpper = IdFactory.getUUIDUpper();
                monthCtrlSub.setId(uuidUpper);
                monthCtrlSub.setSubName(subNameArray[i]);
                monthCtrlSub.setSubOrderIdx(Integer.parseInt(subOrderIdxArray[i]));
                monthCtrlSub.setAddBy(vo.getId());
                monthCtrlSub.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                monthCtrlSubs.add(monthCtrlSub);
            }

            //节点数据处理
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            for (int j = 0; j < showOrderIdxeArray.length; j++ ) {
                MonthCtrlMile monthCtrlMile = new MonthCtrlMile();
                monthCtrlMile.setId(IdFactory.getUUIDUpper());
                monthCtrlMile.setMonthCtrlId(id);
                monthCtrlMile.setCtrlSubId(ctrlSubIdArray[j]);
                monthCtrlMile.setShowOrderIdx(showOrderIdxeArray[j]);
                monthCtrlMile.setLevelIdx(Integer.parseInt(levelIdxeArray[j]));
                monthCtrlMile.setPointName(pointNameArray[j]);
                monthCtrlMile.setMemo(memoArray[j]);
                monthCtrlMile.setPlanStartTime(simpleDateFormat.parse(planStartTimeArray[j]));
                monthCtrlMile.setPlanFinishTime(simpleDateFormat.parse(planFinishTimeArray[j]));
                if (null != actFinishTimeArray[j] && actFinishTimeArray[j].length() > 0) {
                    monthCtrlMile.setActFinishTime(simpleDateFormat.parse(actFinishTimeArray[j]));
                }
                monthCtrlMile.setDelayDays(Integer.parseInt(delayDaysArray[j]));
                monthCtrlMile.setFinishFlag(Integer.parseInt(finishFlagArray[j]));
                monthCtrlMile.setAddBy(vo.getId());
                monthCtrlMile.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                monthCtrlMiles.add(monthCtrlMile);
            }
            
            for (MonthCtrlMile monthCtrlMile : monthCtrlMiles) {
                for (MonthCtrlSub monthCtrlSub : monthCtrlSubs) {
                    if (monthCtrlMile.getCtrlSubId().equals(monthCtrlSub.getSubName())) {
                        monthCtrlMile.setCtrlSubId(monthCtrlSub.getId());
                        break;
                    }
                }
            }
            
            
        }
        
        

        String[] fileAtt = request.getParameterValues("fileAtt");
        /**
         * 上传的文件记录加入集合
         */
        List<MonthCtrlAtt> fileAtts = new ArrayList<MonthCtrlAtt>();
        //附件（选填）
        if (fileAtt != null) {
            for (String file : fileAtt) {
                MonthCtrlAtt monthCtrlAtt = createFileAtt(vo, id, file);
                fileAtts.add(monthCtrlAtt);
            }
        }
        monthCtrlService.saveMonthCtrl(monthCtrl, monthCtrlSubpacks, monthCtrlSubs,
            monthCtrlMiles, fileAtts);
        return RspVo.getSuccessResponse();
    }

    private MonthCtrlAtt createFileAtt(AuthorizationVO vo, String monthCtrlId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        MonthCtrlAtt fileAtt = new MonthCtrlAtt();
        if(StringUtils.isNotEmpty(fileAttStr[1])){
            fileAtt.setId(fileAttStr[1]);
        }else{
            fileAtt.setId(IdFactory.getUUIDUpper());
        }
        fileAtt.setMonthCtrlId(monthCtrlId);//项目id
        String fileName = fileAttStr[0].substring(0, fileAttStr[0].lastIndexOf("."));
        String suffix = fileAttStr[0].substring(fileAttStr[0].lastIndexOf("."),
            fileAttStr[0].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[2]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

//    /**
//     * 通过项目id查询分包付款完成率清单和里程碑节点记录
//     */
//    @RequestMapping("/getInfoByProgramPlanId")
//    @ResponseBody
//    public Map<String, Object> getInfoByProgramInfoId(String id) {
//        boolean flag = true;
//        Map<String, Object> map = new HashMap<>();
//        try {
//            ProgramPlan programPlan = programPlanService.selectByPrimaryKey(id);
//            String proCode = programPlan.getProCode();
//            List<ProgramPlanSubVo> programPlanSubVos = programPlanSubService.selectByProgramPlanId(id);
//            map.put("programPlanSubVos", programPlanSubVos);
//            //根据项目编号查询分包付款合同
//            List<SubpackCotDomain> subpackCots = subpackCotService.selectByProCode(proCode);
//            map.put("subpackCots", subpackCots);
//
//            CitySurvey citySurvey = citySurveyService.selectByPrimaryKey(programPlan.getSgCityId());
//            map.put("sgCityName", citySurvey.getCityName());
//            map.put("sgCityId", citySurvey.getId());
//            map.put("proCode", proCode);
//            map.put("proName", programPlan.getProName());
//            map.put("types", programPlan.getTypes());
//        }
//        catch (Exception e) {
//            log.error("根据投建项目ID获取项目信息异常", e);
//            flag = false;
//        }
//        map.put("flag", flag);
//        return map;
//    }

    /**
     * 上传附件
     *
     * @param request
     * @return
     * @throws IOException
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "monthCtrlAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogUtil.LogModelType.PROJECT, LogUtil.AcctionType.ADD,
                    "投建月度管控附件-文件名:" + filePath + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 根据id查询详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 预立项Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<>();
        MonthCtrlVo monthCtrl = monthCtrlService.selectById(id);

        map.put("monthCtrl", monthCtrl);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, monthCtrl.getProcessId());
        return new ModelAndView("ic/lay-monthCtrl-detail", map);
    }
    
    /**
     * 投建月度管控-复制单据页
     *
     * @param request
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request,String id) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        MonthCtrlVo monthCtrl = monthCtrlService.selectById(id);
        request.setAttribute("monthCtrl", monthCtrl);
        return "ic/lay-monthCtrl-copy";
    }

    /**
     * 根据id查询子项
     * @param id
     * @return
     * @see
     */
    @RequestMapping("/selectSubsById")
    @ResponseBody
    public RspVo<MonthCtrlSub> selectSubsById(String id) {
        MonthCtrlSub t = new MonthCtrlSub();
        t.setMonthCtrlId(id);
        List<MonthCtrlSub> subs = monthCtrlSubService.selectByEntityWhere(t);
        return RspVo.getSuccessResponse(0, subs);
    }

    /**
     * 根据子项id查询里程碑
     * @param id
     * @return
     * @see
     */
    @RequestMapping("/selectMilesById")
    @ResponseBody
    public RspVo<MonthCtrlMile> selectMilesById(String id) {
        List<MonthCtrlMile> miles = monthCtrlMileService.selectBySubId(id);
        return RspVo.getSuccessResponse(0, miles);
    }

}
